<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      <el-form-item label="会员状态" prop="memStatus">
        <el-select v-model="queryParams.memStatus" placeholder="请选择会员状态" clearable style="width: 100%" :filterable="false">
          <el-option label="非会员" value="0"></el-option>
          <el-option label="会员" value="1"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="访问量" prop="visitCount">
        <el-input
          v-model="queryParams.visitCount"
          placeholder="请输入访问量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" 
              :row-style="{height: '40px'}" 
              :cell-style="{padding: '2px 0'}"
              class="user-table"
              border
              stripe>
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="用户ID" align="center" prop="id" width="80" fixed="left" />
      <el-table-column label="用户昵称" align="center" prop="nickname" width="120" show-overflow-tooltip fixed="left" />
      <el-table-column label="用户头像" align="center" prop="avatarUrl" width="100" fixed="left">
        <template slot-scope="scope">
          <div class="avatar-container">
            <el-avatar 
              v-if="scope.row.avatarUrl" 
              :src="scope.row.avatarUrl" 
              :size="28"
              icon="el-icon-user-solid"
              @error="() => handleImageError(scope.row)">
            </el-avatar>
            <el-avatar 
              v-else 
              :size="28"
              icon="el-icon-user-solid"
              background-color="#f5f5f5"
              color="#999">
            </el-avatar>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.gender === 1">男</span>
          <span v-else-if="scope.row.gender === 2">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="所在国家" align="center" prop="country" width="120" show-overflow-tooltip />
      <el-table-column label="省份" align="center" prop="province" width="120" show-overflow-tooltip />
      <el-table-column label="城市" align="center" prop="city" width="120" show-overflow-tooltip />
      <el-table-column label="手机号码" align="center" prop="mobile" width="130" show-overflow-tooltip />
      <el-table-column label="小程序openId" align="center" prop="openId" width="200" show-overflow-tooltip />
      <el-table-column label="小程序unionId" align="center" prop="unionId" width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除时间" align="center" prop="deletedAt" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deletedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="company" width="140" show-overflow-tooltip />
      <el-table-column label="个性签名" align="center" prop="personSign" width="160" show-overflow-tooltip />
      <el-table-column label="会员状态" align="center" prop="memStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.memStatus === 1 ? 'success' : 'info'">
            {{ scope.row.memStatus === 1 ? '会员' : '非会员' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="会员认证时间" align="center" prop="memDate" width="130" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.memDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访问量" align="center" prop="visitCount" width="80" />
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['degree:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['degree:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小程序用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户头像" prop="avatarUrl">
          <image-upload v-model="form.avatarUrl" :limit="1" :file-size="2" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" clearable style="width: 100%" :filterable="false">
            <el-option label="未知" :value="0"></el-option>
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在国家" prop="country">
          <el-input v-model="form.country" placeholder="请输入所在国家" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="form.province" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="小程序openId" prop="openId">
          <el-input v-model="form.openId" placeholder="请输入小程序openId" />
        </el-form-item>
        <el-form-item label="小程序unionId" prop="unionId">
          <el-input v-model="form.unionId" placeholder="请输入小程序unionId" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="删除时间" prop="deletedAt">
          <el-date-picker clearable
            v-model="form.deletedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择删除时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="form.company" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="个性签名" prop="personSign">
          <el-input v-model="form.personSign" type="textarea" placeholder="请输入个性签名" />
        </el-form-item>
        <el-form-item label="会员状态" prop="memStatus">
          <el-select v-model="form.memStatus" placeholder="请选择会员状态" clearable style="width: 100%" :filterable="false">
            <el-option label="非会员" :value="0"></el-option>
            <el-option label="会员" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员认证时间" prop="memDate">
          <el-date-picker clearable
            v-model="form.memDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择会员认证时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="访问量" prop="visitCount">
          <el-input v-model="form.visitCount" placeholder="请输入访问量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/degree/user"
import ImageUpload from "@/components/ImageUpload"

export default {
  name: "User",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        avatarUrl: null,
        gender: null,
        country: null,
        province: null,
        city: null,
        mobile: null,
        openId: null,
        unionId: null,
        createdAt: null,
        updatedAt: null,
        deletedAt: null,
        company: null,
        personSign: null,
        memStatus: null,
        memDate: null,
        visitCount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "小程序openId不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询小程序用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickname: null,
        avatarUrl: null,
        gender: null,
        country: null,
        province: null,
        city: null,
        mobile: null,
        openId: null,
        unionId: null,
        createdAt: null,
        updatedAt: null,
        deletedAt: null,
        company: null,
        personSign: null,
        memStatus: null,
        memDate: null,
        visitCount: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加小程序用户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改小程序用户"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除小程序用户编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('degree/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 图片加载错误处理 */
    handleImageError(row) {
      console.warn('头像加载失败:', row.avatarUrl)
      this.$message.warning(`用户 ${row.nickname || row.id} 的头像加载失败`)
      // 可以在这里设置默认头像
      // row.avatarUrl = '/default-avatar.png'
    }
  }
}
</script>

<style scoped>
/* 用户表格样式 */
.user-table {
  margin-top: 20px;
}

/* 表格行高固定 */
.user-table ::v-deep .el-table__body tr {
  height: 40px;
}

.user-table ::v-deep .el-table__header tr {
  height: 36px;
}

.user-table ::v-deep .el-table td,
.user-table ::v-deep .el-table th {
  padding: 0;
  vertical-align: middle;
  border-right: 1px solid #ebeef5;
}

/* 表格边框和条纹样式 */
.user-table ::v-deep .el-table--border {
  border: 1px solid #ebeef5;
}

.user-table ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fafafa;
}

/* 固定列样式优化 */
.user-table ::v-deep .el-table__fixed {
  box-shadow: 2px 0 6px rgba(0,0,0,0.1);
}

.user-table ::v-deep .el-table__fixed-right {
  box-shadow: -2px 0 6px rgba(0,0,0,0.1);
}

/* 固定列的表头和数据对齐 */
.user-table ::v-deep .el-table__fixed .el-table__header th,
.user-table ::v-deep .el-table__fixed .el-table__body td {
  border-right: 1px solid #ebeef5;
}

.user-table ::v-deep .el-table__fixed-right .el-table__header th,
.user-table ::v-deep .el-table__fixed-right .el-table__body td {
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
}

/* 头像容器样式 */
.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 2px;
}

/* El-Avatar 会自动处理样式，但我们可以添加一些自定义效果 */
.avatar-container ::v-deep .el-avatar {
  border: 1px solid #e8e8e8;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.avatar-container ::v-deep .el-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 统一单元格内容样式 */
.user-table ::v-deep .el-table__body .cell,
.user-table ::v-deep .el-table__header .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.3;
  padding: 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  box-sizing: border-box;
}

/* 表头样式 */
.user-table ::v-deep .el-table__header .cell {
  font-weight: 600;
  color: #303133;
  height: 36px;
}

/* 数据行样式 */
.user-table ::v-deep .el-table__body .cell {
  height: 40px;
}

/* 标签样式优化 */
.user-table ::v-deep .el-tag {
  margin: 0;
  font-weight: 500;
}

/* 操作按钮容器 */
.user-table ::v-deep .small-padding .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 4px;
}

/* 操作按钮样式 */
.user-table ::v-deep .el-button--mini {
  padding: 4px 8px;
  margin: 0;
  font-size: 12px;
  min-width: auto;
}

.user-table ::v-deep .el-button--text {
  border: none;
  background: transparent;
  padding: 4px 8px;
}

.user-table ::v-deep .el-button--text:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 选择框样式 */
.user-table ::v-deep .el-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 表格滚动条样式 */
.user-table ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  height: 8px;
}

.user-table ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.user-table ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

/* Tooltip样式优化 */
.user-table ::v-deep .el-tooltip__popper {
  max-width: 300px;
  word-wrap: break-word;
}

/* 表格行悬停效果 */
.user-table ::v-deep .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 确保所有列宽度一致 */
.user-table ::v-deep .el-table__header-wrapper table,
.user-table ::v-deep .el-table__body-wrapper table,
.user-table ::v-deep .el-table__fixed table,
.user-table ::v-deep .el-table__fixed-right table {
  table-layout: fixed;
  width: 100%;
}

/* 修复固定列边框对齐 */
.user-table ::v-deep .el-table__fixed::before,
.user-table ::v-deep .el-table__fixed-right::before {
  background-color: transparent;
}
</style>
